package com.ophelisis.common.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DateUtils extends DateUtil {
	private static Log	          log	    = LogFactory.getLog(DateUtils.class);
	public static String	      dateSep	= "-";
	public static String	      timeSep	= ":";
	public static String	      dateSep_1	= ".";
	public static final String	      DATETIME_FORMAT_WITH_DAYOFWEEK__15DIGITS	= "yyyyMMddHHmmss+dow";
	public static final String	      DATETIME_FORMAT__14DIGITS	= "yyyyMMddHHmmss";

	private static final String[]	day	    = { "일", "월", "화", "수", "목", "금", "토" };

	public DateUtils() {}

	/**
	 * @return java.util.Date
	 * @param s java.lang.String
	 */
	public java.util.Date check(String s) throws java.text.ParseException {
		return check(s, "yyyyMMdd");
	}

	/**
	 * @return java.util.Date
	 * @param s java.lang.String
	 * @param format .java.lang.String.
	 */
	public java.util.Date check(String str, String format) throws java.text.ParseException {
		if(str == null) throw new java.text.ParseException("date string to check is null", 0);
		if(format == null) throw new java.text.ParseException("format string to check date is null", 0);

		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat(format, java.util.Locale.KOREA);
		java.util.Date date = null;
		try {
			date = formatter.parse(str);
		} catch (java.text.ParseException e) {
			throw new java.text.ParseException(" wrong date:\"" + str + "\" with format \"" + format + "\"", 0);
		}

		if(!formatter.format(date).equals(str)) { throw new java.text.ParseException("Out of bound date:\"" + str + "\" with format \"" + format + "\"", 0); }
		return date;
	}

	/**
	 * check date string validation with the default format "yyyyMMdd".
	 * @param s date string you want to check with default format "yyyyMMdd"
	 * @return boolean true 날짜 형식이 맞고, 존재하는 날짜일 때
	 *                 false 날짜 형식이 맞지 않거나, 존재하지 않는 날짜일 때
	 */
	public boolean isValid(String str) throws Exception {
		return DateUtils.isValid(str, "yyyyMMdd");
	}

	/**
	 * check date string validation with an user defined format.
	 * @param str date string you want to check.
	 * @param format string representation of the date format. For example, "yyyy-MM-dd".
	 * @return boolean true 날짜 형식이 맞고, 존재하는 날짜일 때
	 *                 false 날짜 형식이 맞지 않거나, 존재하지 않는 날짜일 때
	 */
	public static boolean isValid(String str, String format) {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat(format, java.util.Locale.KOREA);
		java.util.Date date = null;
		try {
			date = formatter.parse(str);
		} catch (Exception e) {
			return false;
		}

		if(!formatter.format(date).equals(str)) return false;

		return true;
	}

	/**
	 * @return formatted string representation of current day with  "yyyy-MM-dd".
	 */
	public String getDateString() {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat("yyyy-MM-dd", java.util.Locale.KOREA);
		return formatter.format(new java.util.Date());
	}

	public String getDateString(String pattern) {
		return getYear() + pattern + getMonth() + pattern + getDay();
	}

	public String getDateString(Calendar date) {
		  if (date==null) return "n/a";
	      return date.get(Calendar.YEAR)//+"년 "
	              + "." + (date.get(Calendar.MONTH)+1)// + "월 "
	              + "." + date.get(Calendar.DATE)// + "일"
	              + " " + date.get(Calendar.HOUR)// + "시"
	              + ":" + date.get(Calendar.MINUTE)// + "분"
	              + ":" + date.get(Calendar.SECOND)// + "초"
	              + "." + date.get(Calendar.MILLISECOND)// + "밀리"
	              ;
	  }
	
	public int getTimes() {
		return getNumberByPattern("HH");
	}

	/**
	 *
	 * For example, String time = DateUtil.getFormatString("yyyy-MM-dd HH:mm:ss");
	 *
	 * @param java.lang.String pattern  "yyyy, MM, dd, HH, mm, ss and more"
	 * @return formatted string representation of current day and time with  your pattern.
	 */
	public int getDay() {
		return getNumberByPattern("dd");
	}

	/**
	*
	* For example, String time = DateUtil.getFormatString("yyyy-MM-dd HH:mm:ss");
	*
	* @param java.lang.String pattern  "yyyy, MM, dd, HH, mm, ss and more"
	* @return formatted string representation of current day and time with  your pattern.
	*/
	public int getYear() {
		return getNumberByPattern("yyyy");
	}

	/**
	 *
	 * For example, String time = DateUtil.getFormatString("yyyy-MM-dd HH:mm:ss");
	 *
	 * @param java.lang.String pattern  "yyyy, MM, dd, HH, mm, ss and more"
	 * @return formatted string representation of current day and time with  your pattern.
	 */
	public int getMonth() {
		return getNumberByPattern("MM");
	}

	/**
	 *
	 * For example, String time = DateUtil.getFormatString("yyyy-MM-dd HH:mm:ss");
	 *
	 * @param java.lang.String pattern  "yyyy, MM, dd, HH, mm, ss and more"
	 * @return formatted string representation of current day and time with  your pattern.
	 */
	public int getNumberByPattern(String pattern) {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat(pattern, java.util.Locale.KOREA);
		String dateString = formatter.format(new java.util.Date());
		return Integer.parseInt(dateString);
	}

	public int getMinute() {
		return getNumberByPattern("mm");
	}

	public int getSecond() {
		return getNumberByPattern("ss");
	}

	/**
	 *
	 * For example, String time = DateUtil.getFormatString("yyyy-MM-dd HH:mm:ss");
	 *
	 * @param java.lang.String pattern  "yyyy, MM, dd, HH, mm, ss and more"
	 * @return formatted string representation of current day and time with  your pattern.
	 */
	public String getFormatString(String pattern) {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat(pattern, java.util.Locale.KOREA);
		String dateString = formatter.format(new java.util.Date());
		return dateString;
	}

	/**
	 * @return formatted string representation of current day with  "yyyyMMdd".
	 */
	public String getShortDateString() {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat("yyyyMMdd", java.util.Locale.KOREA);
		return formatter.format(new java.util.Date());
	}

	/**
	 * @return formatted string representation of srcDate.
	 */
	public String getDateToString(java.util.Date srcDate) throws Exception {
		StringBuffer sb = null;
		Calendar cal = null;
		try {
			cal = Calendar.getInstance();
			cal.setTime(srcDate);
			sb = new StringBuffer(18);
			sb.append(new SimpleDateFormat("yyyyMMddHHmmss", java.util.Locale.KOREA).format(srcDate));
			sb.append(String.valueOf(cal.get(Calendar.DAY_OF_WEEK)));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("getDateToString()", e);
			throw e;
		}
		return sb.toString();
	}

	/**
	 * @return formatted string representation of current time with  "HHmmss".
	 */
	public String getShortTimeString() {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat("HHmmss", java.util.Locale.KOREA);
		return formatter.format(new java.util.Date());
	}

	/**
	 * @return formatted string representation of current time with  "yyyy-MM-dd-HH:mm:ss".
	 */
	public String getTimeStampString() {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat("yyyy-MM-dd-HH:mm:ss:SSS", java.util.Locale.KOREA);
		return formatter.format(new java.util.Date());
	}

	/**
	 * @return formatted string representation of current time with  "HH:mm:ss".
	 */
	public String getTimeString() {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat("HH:mm:ss", java.util.Locale.KOREA);
		return formatter.format(new java.util.Date());
	}

	/**
	 * return days between two date strings with default defined format.(yyyyMMdd)
	 * @param s date string you want to check.
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 요일을 리턴
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 *          0: 일요일 (java.util.Calendar.SUNDAY 와 비교)
	 *          1: 월요일 (java.util.Calendar.MONDAY 와 비교)
	 *          2: 화요일 (java.util.Calendar.TUESDAY 와 비교)
	 *          3: 수요일 (java.util.Calendar.WENDESDAY 와 비교)
	 *          4: 목요일 (java.util.Calendar.THURSDAY 와 비교)
	 *          5: 금요일 (java.util.Calendar.FRIDAY 와 비교)
	 *          6: 토요일 (java.util.Calendar.SATURDAY 와 비교)
	 * 예) String s = "20000529";
	 *  int dayOfWeek = whichDay(s, format);
	 *  if (dayOfWeek == java.util.Calendar.MONDAY)
	 *      System.out.println(" 월요일: " + dayOfWeek);
	 *  if (dayOfWeek == java.util.Calendar.TUESDAY)
	 *      System.out.println(" 화요일: " + dayOfWeek);
	 */
	public int whichDay(String s) throws java.text.ParseException {
		return whichDay(s, "yyyyMMdd");
	}

	/**
	 * return days between two date strings with user defined format.
	 * @param s date string you want to check.
	 * @param format string representation of the date format. For example, "yyyy-MM-dd".
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 요일을 리턴
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 *          0: 일요일 (java.util.Calendar.SUNDAY 와 비교)
	 *          1: 월요일 (java.util.Calendar.MONDAY 와 비교)
	 *          2: 화요일 (java.util.Calendar.TUESDAY 와 비교)
	 *          3: 수요일 (java.util.Calendar.WENDESDAY 와 비교)
	 *          4: 목요일 (java.util.Calendar.THURSDAY 와 비교)
	 *          5: 금요일 (java.util.Calendar.FRIDAY 와 비교)
	 *          6: 토요일 (java.util.Calendar.SATURDAY 와 비교)
	 * 예) String s = "2000-05-29";
	 *  int dayOfWeek = whichDay(s, "yyyy-MM-dd");
	 *  if (dayOfWeek == java.util.Calendar.MONDAY)
	 *      System.out.println(" 월요일: " + dayOfWeek);
	 *  if (dayOfWeek == java.util.Calendar.TUESDAY)
	 *      System.out.println(" 화요일: " + dayOfWeek);
	 */
	public int whichDay(String s, String format) throws java.text.ParseException {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat(format, java.util.Locale.KOREA);
		java.util.Date date = check(s, format);

		java.util.Calendar calendar = formatter.getCalendar();
		calendar.setTime(date);
		return calendar.get(java.util.Calendar.DAY_OF_WEEK);
	}

	/**
	 * return days between two date strings with default defined format.("yyyyMMdd")
	 * @param String from date string
	 * @param String to date string
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 2개 일자 사이의 나이 리턴
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 */
	public int daysBetween(String from, String to) throws java.text.ParseException {
		return daysBetween(from, to, "yyyyMMdd");
	}

	/**
	 * return days between two date strings with user defined format.
	 * @param String from date string
	 * @param String to date string
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 2개 일자 사이의 일자 리턴
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 */
	public int daysBetween(String from, String to, String format) throws java.text.ParseException {
		//SafeSimpleDateFormat formatter =
		//new SafeSimpleDateFormat(format, java.util.Locale.KOREA);
		java.util.Date d1 = check(from, format);
		java.util.Date d2 = check(to, format);

		long duration = d2.getTime() - d1.getTime();

		return (int) (duration / (1000 * 60 * 60 * 24));
		// seconds in 1 day
	}

	/**
	 * return age between two date strings with default defined format.("yyyyMMdd")
	 * @param String from date string
	 * @param String to date string
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 2개 일자 사이의 나이 리턴
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 */
	public int ageBetween(String from, String to) throws java.text.ParseException {
		return ageBetween(from, to, "yyyyMMdd");
	}

	/**
	 * return age between two date strings with user defined format.
	 * @param String from date string
	 * @param String to date string
	 * @param format string representation of the date format. For example, "yyyy-MM-dd".
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 2개 일자 사이의 나이 리턴
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 */
	public int ageBetween(String from, String to, String format) throws java.text.ParseException {
		return (int) (daysBetween(from, to, format) / 365);
	}

	/**
	 * return minutes between two date strings with default defined format.("yyyyMMddHHmmss")
	 * @param String from date string
	 * @param String to date string
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 2개 일자 사이의 분 리턴
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 */
	public int minutesBetween(String from, String to) throws java.text.ParseException {
		return minutesBetween(from, to, "yyyyMMddHHmmss");
	}

	/**
	 * return minutes between two date strings with user defined format.
	 * @param String from date string
	 * @param String to date string
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 2개 일자 사이의 분 리턴
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 */
	public int minutesBetween(String from, String to, String format) throws java.text.ParseException {
		//SafeSimpleDateFormat formatter = new SafeSimpleDateFormat (format, java.util.Locale.KOREA);
		java.util.Date d1 = check(from, format);
		java.util.Date d2 = check(to, format);

		long duration = d2.getTime() - d1.getTime();

		return (int) (duration / (1000 * 60));
	}
	
	/** 두 시간의 차이를 구한다. */
	public static long getBetweenDateTime(String from, String to) {
		return getBetweenDateTime(parseDate(from), parseDate(to));
	}

	/** 두 시간의 차이를 구한다. */
	public static long getBetweenDateTime(Date from, Date to) {
		return to.getTime() - from.getTime();
	}

	/** 두 시간의 차이를 구한다. (날짜) */
	public static int getBetweenDays(String from, String to) {
		// return Integer.parseInt(to.substring(0, 8)) -
		// Integer.parseInt(from.substring(0, 8));
		long gap = getBetweenDateTime(from, to);
		// long time = 1000; //1초
		// time *= 60; //1분
		// time *= 60; //1시간
		// time *= 24; //1일
		long time = 86400000;
		return (int) (gap / time);
	}
	
	/**
	 * 입력문자열을 Date객체로 리턴한다. 날짜입력형태 20070901220103, 200709012 등..
	 */
	public static Date parseDate(String str) {
		return ymdToDate(StringUtil.rpad(trim(str), 14, "0"), "yyyyMMddHHmmss");
	}
		
	/** 날짜 중간에 삽입된 기호들을 제거한다. */
	public static String trim(String str) {
		if (str == null)
			return null;
		return str.trim().replaceAll("[-/\\. :]", "");
	}
	
	// 날짜 관련 Start ***************************************************//
		public static String dateToYmd(Date date, String formatOut) {
			String strOut = null;
			SimpleDateFormat formatter = null;
			try {
				formatter = new SimpleDateFormat(formatOut, Locale.KOREA);
				strOut = formatter.format(date);
			} catch (Exception e) {
				return strOut;
			}
			return strOut;
		}

		public static Date ymdToDate(String strIn, String formatIn, Locale locale) {
			Date date = null;
			SimpleDateFormat formatter = null;
			try {
				formatter = new SimpleDateFormat(formatIn, locale);
				date = formatter.parse(strIn);
			} catch (Exception e) {
				return date;
			}
			return date;
		}

		public static Date ymdToDate(String strIn, String formatIn) {
			return ymdToDate(strIn, formatIn, Locale.KOREA);
		}

		// ymdToYmd("20070704131610", "yyyyMMddHHmmss", "yyyy-MM-dd a hh:mm")
		public static String ymdToYmd(String strIn, String formatIn,
				String formatOut) {
			Date date = ymdToDate(strIn, formatIn);
			return date == null ? "" : dateToYmd(date, formatOut);
		}

	/**
	 * return add day to date strings
	 * @param String date string
	 * @param int 더할 일수
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 일수 더하기
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 */
	public String addDays(String s, int day) throws java.text.ParseException {
		return addDays(s, day, "yyyyMMdd");
	}

	/**
	 * return add day to date strings with user defined format.
	 * @param String date string
	 * @param int 더할 일수
	 * @param format string representation of the date format. For example, "yyyy-MM-dd".
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 일수 더하기
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 */
	public String addDays(String s, int day, String format) throws java.text.ParseException {
		boolean isNeedDow = StringUtils.isNotEmpty(format) && format.equals(DATETIME_FORMAT_WITH_DAYOFWEEK__15DIGITS);
		String fmt = isNeedDow ? DATETIME_FORMAT__14DIGITS : format;
		
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat(fmt, java.util.Locale.KOREA);
		java.util.Date date = check(s, fmt);

		date.setTime(date.getTime() + ((long) day * 1000 * 60 * 60 * 24));
		
		String dow = "";
		if(isNeedDow)
		{
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			dow = String.valueOf(cal.get(Calendar.DAY_OF_WEEK));
		}
		
		return formatter.format(date)+dow;
	}

	/**
	 * return add month to date strings
	 * @param String date string
	 * @param int 더할 월수
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 월수 더하기
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 */
	public String addMonths(String s, int month) throws Exception {
		return addMonths(s, month, "yyyyMMdd");
	}

	/**
	 * return add month to date strings with user defined format.
	 * @param String date string
	 * @param int 더할 월수
	 * @param format string representation of the date format. For example, "yyyy-MM-dd".
	 * @return int 날짜 형식이 맞고, 존재하는 날짜일 때 월수 더하기
	 *           형식이 잘못 되었거나 존재하지 않는 날짜: java.text.ParseException 발생
	 */
	public String addMonths(String s, int addMonth, String format) throws Exception {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat(format, java.util.Locale.KOREA);
		java.util.Date date = check(s, format);

		SafeSimpleDateFormat yearFormat = new SafeSimpleDateFormat("yyyy", java.util.Locale.KOREA);
		SafeSimpleDateFormat monthFormat = new SafeSimpleDateFormat("MM", java.util.Locale.KOREA);
		SafeSimpleDateFormat dayFormat = new SafeSimpleDateFormat("dd", java.util.Locale.KOREA);
		int year = Integer.parseInt(yearFormat.format(date));
		int month = Integer.parseInt(monthFormat.format(date));
		int day = Integer.parseInt(dayFormat.format(date));

		month += addMonth;
		if(addMonth > 0) {
			while (month > 12) {
				month -= 12;
				year += 1;
			}
		} else {
			while (month <= 0) {
				month += 12;
				year -= 1;
			}
		}
		java.text.DecimalFormat fourDf = new java.text.DecimalFormat("0000");
		java.text.DecimalFormat twoDf = new java.text.DecimalFormat("00");
		String tempDate = String.valueOf(fourDf.format(year)) + String.valueOf(twoDf.format(month)) + String.valueOf(twoDf.format(day));
		java.util.Date targetDate = null;

		try {
			targetDate = check(tempDate, "yyyyMMdd");
		} catch (java.text.ParseException pe) {
			day = lastDay(year, month);
			tempDate = String.valueOf(fourDf.format(year)) + String.valueOf(twoDf.format(month)) + String.valueOf(twoDf.format(day));
			targetDate = check(tempDate, "yyyyMMdd");
		}

		return formatter.format(targetDate);
	}

	public String addYears(String s, int year) throws java.text.ParseException {
		return addYears(s, year, "yyyyMMdd");
	}

	public String addYears(String s, int year, String format) throws java.text.ParseException {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat(format, java.util.Locale.KOREA);
		java.util.Date date = check(s, format);
		date.setTime(date.getTime() + ((long) year * 1000 * 60 * 60 * 24 * (365 + 1)));
		return formatter.format(date);
	}

	public int monthsBetween(String from, String to) throws java.text.ParseException {
		return monthsBetween(from, to, "yyyyMMdd");
	}

	public int monthsBetween(String from, String to, String format) throws java.text.ParseException {
		//SafeSimpleDateFormat formatter =
		//    new SafeSimpleDateFormat (format, java.util.Locale.KOREA);
		java.util.Date fromDate = check(from, format);
		java.util.Date toDate = check(to, format);

		// if two date are same, return 0.
		if(fromDate.compareTo(toDate) == 0) return 0;

		SafeSimpleDateFormat yearFormat = new SafeSimpleDateFormat("yyyy", java.util.Locale.KOREA);
		SafeSimpleDateFormat monthFormat = new SafeSimpleDateFormat("MM", java.util.Locale.KOREA);
		SafeSimpleDateFormat dayFormat = new SafeSimpleDateFormat("dd", java.util.Locale.KOREA);

		int fromYear = Integer.parseInt(yearFormat.format(fromDate));
		int toYear = Integer.parseInt(yearFormat.format(toDate));
		int fromMonth = Integer.parseInt(monthFormat.format(fromDate));
		int toMonth = Integer.parseInt(monthFormat.format(toDate));
		int fromDay = Integer.parseInt(dayFormat.format(fromDate));
		int toDay = Integer.parseInt(dayFormat.format(toDate));

		int result = 0;
		result += ((toYear - fromYear) * 12);
		result += (toMonth - fromMonth);

		//        if (((toDay - fromDay) < 0) ) result += fromDate.compareTo(toDate);
		// ceil�� floor�� ȿ��
		if(((toDay - fromDay) > 0)) result += toDate.compareTo(fromDate);

		return result;
	}

	public String lastDayOfMonth(String src) throws java.text.ParseException {
		return lastDayOfMonth(src, "yyyyMMdd");
	}

	public String lastDayOfMonth(String src, String format) throws java.text.ParseException {
		SafeSimpleDateFormat formatter = new SafeSimpleDateFormat(format, java.util.Locale.KOREA);
		java.util.Date date = check(src, format);

		SafeSimpleDateFormat yearFormat = new SafeSimpleDateFormat("yyyy", java.util.Locale.KOREA);
		SafeSimpleDateFormat monthFormat = new SafeSimpleDateFormat("MM", java.util.Locale.KOREA);

		int year = Integer.parseInt(yearFormat.format(date));
		int month = Integer.parseInt(monthFormat.format(date));
		int day = lastDay(year, month);

		java.text.DecimalFormat fourDf = new java.text.DecimalFormat("0000");
		java.text.DecimalFormat twoDf = new java.text.DecimalFormat("00");
		String tempDate = String.valueOf(fourDf.format(year)) + String.valueOf(twoDf.format(month)) + String.valueOf(twoDf.format(day));
		date = check(tempDate, format);

		return formatter.format(date);
	}

	private int lastDay(int year, int month) throws java.text.ParseException {
		int day = 0;
		switch (month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			day = 31;
			break;
		case 2:
			if((year % 4) == 0) {
				if((year % 100) == 0 && (year % 400) != 0) {
					day = 28;
				} else {
					day = 29;
				}
			} else {
				day = 28;
			}
			break;
		default:
			day = 30;
		}
		return day;
	}

	public String DatetoString(java.util.Date date) {
		if(date == null) return "";
		else {
			DateFormat dateformat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.KOREA);
			String str = dateformat.format(date).toString();
			return str;
		}
	}

	public String StringtoYmd(String date) throws Exception {
		StringBuffer ymd = null;

		if(date == null || "".equals(date)) return null;
		try {
			ymd = new StringBuffer(100);
			ymd.append(date.substring(0, 4));
			ymd.append("-").append(date.substring(4, 6));
			ymd.append("-").append(date.substring(6, 8));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("StringtoYmd()", e);
			throw e;
		}

		return ymd.toString();
	}

	public String TimestamptoString(Timestamp time) {
		if(time == null) return "";
		else {
			String str = time.toString();
			return str.substring(0, 19);
		}
	}

	public Timestamp StringtoTimestamp(String str) throws NumberFormatException {
		int year = 0, month = 0, day = 0;
		int hour = 0, minute = 0, second = 0;//, nano = 0;

		StringTokenizer st = new StringTokenizer(str);
		if(st.hasMoreTokens()) {
			StringTokenizer token = new StringTokenizer(st.nextToken(), "-");
			if(token.hasMoreTokens()) year = Integer.parseInt(token.nextToken());
			if(token.hasMoreTokens()) month = Integer.parseInt(token.nextToken());
			if(token.hasMoreTokens()) day = Integer.parseInt(token.nextToken());
		} else {
			throw new NumberFormatException(str);
		}
		if(st.hasMoreTokens()) {
			StringTokenizer token = new StringTokenizer(st.nextToken(), ":");
			if(token.hasMoreTokens()) hour = Integer.parseInt(token.nextToken());
			if(token.hasMoreTokens()) minute = Integer.parseInt(token.nextToken());
			if(token.hasMoreTokens()) second = Integer.parseInt(token.nextToken());
		}

		Calendar c = Calendar.getInstance();
		c.set(year, month - 1, day, hour, minute, second);

		return new Timestamp(c.getTime().getTime());
	}

	public String createTimeString() {
		StringBuffer sb = null;
		Calendar cal = null;
		try {
			cal = Calendar.getInstance();
			sb = new StringBuffer(18);
			sb.append(new SimpleDateFormat("yyyyMMddHHmmss", java.util.Locale.KOREA).format(new java.util.Date()));
			sb.append(String.valueOf(cal.get(Calendar.DAY_OF_WEEK)));
		} catch (Exception e) {
			log.error("createTimeString()", e);
		}
		return sb.toString();
	}

	public String createTimeSubString() throws Exception {
		StringBuffer sb = null;
		try {
			sb = new StringBuffer(18);
			sb.append(new SimpleDateFormat("yyyyMMddHHmmss", java.util.Locale.KOREA).format(new java.util.Date()));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("createTimeSubString()", e);
			throw e;
		}
		return sb.toString();
	}

	public String lastDateOfMonth() throws Exception {
		StringBuffer dateStr = null;
		int year = 0, month = 0, date = 0;
		Calendar cal = null;
		try {
			year = getYear();
			month = getMonth();
			date = lastDay(getYear(), getMonth());

			cal = Calendar.getInstance();
			cal.set(Calendar.YEAR, year);
			cal.set(Calendar.MONTH, month - 1);
			cal.set(Calendar.DATE, date);
			dateStr = new StringBuffer(18);
			dateStr.append(lastDayOfMonth(getShortDateString()));
			dateStr.append("235959");
			dateStr.append(cal.get(Calendar.DAY_OF_WEEK));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("lastDateOfMonth()", e);
			throw e;
		}
		return dateStr.toString();
	}

	public String getDayOfWeek() {
		Calendar c = Calendar.getInstance();
		return day[c.get(java.util.Calendar.DAY_OF_WEEK) - 1];
	}

	public static String getDateTimeString15Digits() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssS");
		return sdf.format(cal.getTime()).substring(0, 15);
	}

	public static void main(String args[]) {
		try {
			DateUtils du = new DateUtils();
			int minutes = 720;
			System.out.println(" Convert "+ minutes + " Minutes ==> "+du.convertHoursFromMinutes(minutes)+" Hours.");
		} catch (Exception e) {}

	}

	public boolean leftOlderThenRight(String s, java.util.Date date) throws java.text.ParseException {
		return leftOlderThenRight(s, "yyyyMMddHHmmssS", date);
	}

	public boolean leftOlderThenRight(String s, String format, java.util.Date date) throws java.text.ParseException {
		java.util.Date s_date = check(s, format);
		return s_date.compareTo(date) < 0 ? true : false;
	}
	
	public int convertHoursFromMinutes(String minutesStr) {
		int minutes = StringUtil.getInteger(minutesStr);
		return convertHoursFromMinutes(minutes);
	}
	public int convertHoursFromMinutes(int minutes) {
		int hours = (minutes % 60)>0?1+(minutes / 60):(minutes / 60);
		return hours;
	}
	public int convertDaysFromMinutes(String minutesStr) {
		int minutes = StringUtil.getInteger(minutesStr);
		return convertDaysFromMinutes(minutes);
	}
	public int convertDaysFromMinutes(int minutes) {
		int hours = (minutes % 60)>0?1+(minutes / 60):(minutes / 60);
		return convertDaysFromHours(hours);
	}
	public int convertDaysFromHours(String hoursStr) {
		int hours = StringUtil.getInteger(hoursStr);
		return convertDaysFromHours(hours);
	}
	public int convertDaysFromHours(int hours) {
		int days = 0;
		days = (hours % 24)>0?1+(hours / 24):(hours / 24);
		return days;
	}
}
